package com.snc.controller.system;

import com.snc.annotation.SystemLog;
import com.snc.controller.index.BaseController;
import com.snc.entity.Params;
import com.snc.entity.ResFormMap;
import com.snc.entity.ResUserFormMap;
import com.snc.entity.UserRoleFormMap;
import com.snc.exception.SystemException;
import com.snc.util.Common;
import com.snc.util.JsonUtils;
import com.snc.util.TreeObject;
import com.snc.util.TreeUtil;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author lanyuan 
 * @date  2015-11-19
 * @Email: mmm333zzz520@163.com
 * @version 4.0v
 */
@Controller
@RequestMapping("/resources/")
public class ResourcesController extends BaseController {

	/**
	 * @param model
	 *            存放返回界面的model
	 * @return
	 */
	@ResponseBody
	@RequestMapping("treelists")
	public ResFormMap findByPage(Model model) {
		ResFormMap resFormMap = getFormMap(ResFormMap.class);
		String order = " order by level asc";
		resFormMap.put("$orderby", order);
		List<ResFormMap> mps = resFormMap.findByNames();
		List<TreeObject> list = new ArrayList<TreeObject>();
		for (ResFormMap map : mps) {
			TreeObject ts = new TreeObject();
			Common.flushObject(ts, map);
			list.add(ts);
		}
		TreeUtil treeUtil = new TreeUtil();
		List<TreeObject> ns = treeUtil.getChildTreeObjects(list, 0);
		resFormMap = new ResFormMap();
		resFormMap.put("treelists", ns);
		return resFormMap;
	}

	@ResponseBody
	@RequestMapping("reslists")
	public List<TreeObject> reslists(Model model) throws Exception {
		ResFormMap resFormMap = getFormMap(ResFormMap.class);
		List<ResFormMap> mps = resFormMap.findByWhere();
		List<TreeObject> list = new ArrayList<TreeObject>();
		for (ResFormMap map : mps) {
			TreeObject ts = new TreeObject();
			Common.flushObject(ts, map);
			list.add(ts);
		}
		TreeUtil treeUtil = new TreeUtil();
		List<TreeObject> ns = treeUtil.getChildTreeObjects(list, 0, "　");
		return ns;
	}

	/**
	 * @param model
	 *            存放返回界面的model
	 * @return
	 */
	@RequestMapping("listUI")
	public String list(Model model) {
		model.addAttribute("res", findByRes());
		return Common.BACKGROUND_PATH + "/system/resources/list";
	}

	/**
	 * 跳转到修改界面
	 * 
	 * @param model
	 * @param resourcesId
	 *            修改菜单信息ID
	 * @return
	 */
	@RequestMapping("editUI")
	public String editUI(Model model) {
		String id = getPara("id");
		if(Common.isNotEmpty(id)){
			ResFormMap resFormMap =  new ResFormMap(); 
			model.addAttribute("resources", resFormMap.findById(id));
		}
		return Common.BACKGROUND_PATH + "/system/resources/edit";
	}

	/**
	 * 跳转到新增界面
	 * 
	 * @return
	 */
	@RequestMapping("addUI")
	public String addUI(Model model) {
		return Common.BACKGROUND_PATH + "/system/resources/add";
	}

	/**
	 * 权限分配页面
	 * 
	 * @author lanyuan Email：mmm333zzz520@163.com date：2015-4-14
	 * @param model
	 * @return
	 */
	@RequestMapping("permissions")
	public String permissions(Model model) {
		ResFormMap resFormMap = getFormMap(ResFormMap.class);
		List<ResFormMap> mps = resFormMap.findByWhere();
		for (ResFormMap resFormMap2 : mps) {
			resFormMap2.remove("description");
			resFormMap2.remove("resUrl");
			resFormMap2.remove("resKey");
			resFormMap2.remove("icon");
		}
		model.addAttribute("permissions", JsonUtils.listToJson(mps));
		return Common.BACKGROUND_PATH + "/system/resources/permissions";
	}

	/**
	 * 添加菜单
	 * 
	 * @param resources
	 * @return Map
	 * @throws Exception
	 */
	@RequestMapping("addEntity")
	@ResponseBody
	@Transactional//需要事务操作必须加入此注解
	@SystemLog(module="系统管理",methods="资源管理-新增资源")//凡需要处理业务逻辑的.都需要记录操作日志
	public String addEntity() throws Exception {
		try {
			ResFormMap resFormMap = getFormMap(ResFormMap.class);
			Object o = resFormMap.get("ishide");
			if (null == o) {
				resFormMap.put("ishide", "0");
			}
			String btnId = getPara("btnId");
			String btnName = getPara("btnName");
			String btnClass = getPara("btnClass");
			String btnValue = getPara("btnValue");
			if(Common.isNotEmpty(btnId))
			resFormMap.put("btn", btnId+","+btnName+","+btnClass+","+btnValue);
			resFormMap.save();
		} catch (Exception e) {
			//try catch 必须抛出自定义异常,否则事务失效!   #### lanyuan ####
			String results = "{\"results\":\"error\",\"message\":\""+e+"\"}";
			throw new SystemException(results);
		}
		
		return "success";
	}

	/**
	 * 更新菜单
	 * 
	 * @param model
	 * @param Map
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("editEntity")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="系统管理",methods="资源管理-修改资源")//凡需要处理业务逻辑的.都需要记录操作日志
	public String editEntity(Model model) throws Exception {
		try {
			ResFormMap resFormMap = getFormMap(ResFormMap.class);
			Object o = resFormMap.get("ishide");
			if (null == o) {
				resFormMap.put("ishide", "0");
			}
			String btnId = getPara("btnId");
			String btnName = getPara("btnName");
			String btnClass = getPara("btnClass");
			String btnValue = getPara("btnValue");
			if(Common.isNotEmpty(btnId))
			resFormMap.put("btn", btnId+","+btnName+","+btnClass+","+btnValue);
			resFormMap.update();
		} catch (Exception e) {
			//try catch 必须抛出自定义异常,否则事务失效!   #### lanyuan ####
			String results = "{\"results\":\"error\",\"message\":\""+e+"\"}";
			throw new SystemException(results);
		}
		return "success";
	}

	/**
	 * 根据ID删除菜单
	 * 
	 * @param model
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("deleteEntity")
	@SystemLog(module="系统管理",methods="资源管理-删除资源")//凡需要处理业务逻辑的.都需要记录操作日志
	public String deleteEntity(String ids) throws Exception {
		ResFormMap resFormMap = new ResFormMap();
		resFormMap.deleteByAttribute("id", ids);
		return "success";
	}

	@RequestMapping("sortUpdate")
	@ResponseBody
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	public String sortUpdate(Params params) throws Exception {
		List<String> ids = params.getId();
		List<String> es = params.getRowId();
		List<ResFormMap> maps = new ArrayList<ResFormMap>();
		ResFormMap map = null;
		for (int i = 0; i < ids.size(); i++) {
			 map = new ResFormMap();
			map.put("id", ids.get(i));
			map.put("level", es.get(i));
			maps.add(map);
		}
		ResFormMap.mapper().updateSortOrder(maps);
		return "success";
	}

	@ResponseBody
	@RequestMapping("findRes")
	public List<ResFormMap> findUserRes() {
		ResFormMap resFormMap = getFormMap(ResFormMap.class);
		List<ResFormMap> rs = ResFormMap.mapper().findRes(resFormMap);
		return rs;
	}
	@ResponseBody
	@RequestMapping("addUserRes")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="系统管理",methods="用户管理/角色管理-修改权限")//凡需要处理业务逻辑的.都需要记录操作日志
	public String addUserRes() throws Exception {
		try {
			String userId = "";
			String u = getPara("userId");
			String g = getPara("roleId");
			String resId = getPara("resId");
			if (null != u && !Common.isEmpty(u.toString())) {
				userId = u.toString();
			} else if (null != g && !Common.isEmpty(g.toString())) {
				UserRoleFormMap userRoleFormMap = new UserRoleFormMap();
				List<UserRoleFormMap> gs = userRoleFormMap.findByAttribute("roleId", g.toString());
				if (gs.size() == 0) {
					return "操作失败:..该组下没有分配任何用户!";
				}
				for (UserRoleFormMap ug : gs) {
					userId += ug.get("userId") + ",";
				}
			}
			userId = Common.trimComma(userId);
			String[] users = userId.split(",");
			for (String uid : users) {
				ResUserFormMap resUserFormMap = new ResUserFormMap();
				resUserFormMap.deleteByAttribute("userId", uid);
				String[] s = Common.trimComma(resId).split(",");
				List<ResUserFormMap> resUserFormMaps = new ArrayList<ResUserFormMap>();
				for (String rid : s) {
					ResUserFormMap formMap = new ResUserFormMap();
					formMap.put("resId", rid);
					formMap.put("userId", uid);
					resUserFormMaps.add(formMap);
				}
				resUserFormMap.batchSave(resUserFormMaps);
			}
		} catch (Exception e) {
			//try catch 必须抛出自定义异常,否则事务失效!   #### lanyuan ####
			String results = "{\"results\":\"error\",\"message\":\""+e+"\"}";
			throw new SystemException(results);
		}
		return "success";
	}

	/**
	 * 验证菜单是否存在
	 * 
	 * @param name
	 * @return
	 */
	@RequestMapping("isExist")
	@ResponseBody
	public boolean isExist(String name,String resKey) {
		ResFormMap resFormMap = getFormMap(ResFormMap.class);
		List<ResFormMap> r = resFormMap.findByNames();
		if (r.size()==0) {
			return true;
		} else {
			return false;
		}
	}
}